package com.qlslylq.ad.example.activity;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qlslylq.ad.example.R;
import com.qlslylq.ad.example.adapter.FeedAdapter;
import com.qlslylq.ad.example.constant.KeyConst;
import com.qlslylq.ad.example.model.NormalItem;
import com.qlslylq.ad.sdk.core.ad.SingleFeedAd;
import com.qlslylq.ad.sdk.core.listener.FeedAdListener;
import com.qlslylq.ad.sdk.core.loader.FeedAdLoader;
import com.qlslylq.ad.sdk.core.rsp.AdError;
import com.qlslylq.ad.sdk.util.DensityUtils;
import com.qlslylq.ad.sdk.util.DeviceUtil;
import com.qlslylq.ad.sdk.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;

/**
 * 信息流广告测试页<br/>
 */
public class FeedAdTestMainActivity extends BaseActivity {

    private static final int ITEMS_COUNT = 10;
    private static final int AD_COUNT = 1;    // 加载广告的条数，取值范围为[1, 3]
    private static int FIRST_AD_POSITION = 1; // 第一条广告的位置
    private static int ITEMS_PER_AD = 5;     // 每间隔10个条目插入一条广告

    private RecyclerView recyclerView;

    private FeedAdLoader loader;

    private boolean isResetData = false;

    private boolean isLoading = true;

    private FeedAdapter adapter;

    private List<NormalItem> normalDataList = new ArrayList<>();

    private List<SingleFeedAd> adDataList = new ArrayList<>();

    private HashMap<SingleFeedAd, Integer> adPosMap = new HashMap<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_ad_test_main);
    }

    protected void initView() {
        setTitle("信息流广告测试");
        recyclerView = findView(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!isLoading && newState == SCROLL_STATE_IDLE && !recyclerView.canScrollVertically(1)) {
                    isLoading = true;
//                    loader.show();
                }
            }
        });
    }

    protected void initData() {
        initLoader();
        fillRecyclerViewData();
    }

    protected void initListener() {

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_0:
                reverseScreenOrientation();
                break;
            case R.id.btn_1:
                loader.load();
                break;
            case R.id.btn_2:
                isResetData = true;
                loader.show();
                break;
            case R.id.btn_3:
                isResetData = false;
                loader.show();
                break;
            case R.id.btn_4:
                isResetData = true;
                loader.loadAndShow();
                break;
            case R.id.btn_5:
                isResetData = false;
                loader.loadAndShow();
                break;
            case R.id.btn_6:
                showToast("正在开发中~");
                break;
        }
    }

    private void initLoader() {
        if (loader == null) {
//            横版样式测试(需要广告位样式选择域配合，需要请求物料尺寸配合)
            float expressWidth = DeviceUtil.getScreenWidth(this) - DensityUtils.dp2px(this, 20);//减去的左右边距之和，必须与list_item_feed_ad.xml中的左右边距之和严格对应
            loader = new FeedAdLoader(this, KeyConst.JH_FEED_POS_ID, expressWidth, 0, AD_COUNT, false, new FeedAdListener() {

                //            竖版样式测试(需要广告位样式选择域配合，需要请求物料尺寸配合)
//            float expressWidth = DensityUtils.dp2px(this, 110);
//            float expressHeight = DensityUtils.dp2px(this, 188);
//            loader = new FeedAdLoader(this, KeyConst.JH_FEED_POS_ID, expressWidth, expressHeight, AD_COUNT, false, new FeedAdListener() {
                public void onAdReadyShow(List<SingleFeedAd> list) {
                    Log.i("onAdReadyShow");
                    isLoading = false;
                    if (isResetData) {
                        adapter.getList().clear();
                        normalDataList.clear();
                        adDataList.clear();
                        adPosMap.clear();
                    }
                    loadAds(list);
                    adapter.notifyDataSetChanged();
                }

                public void onAdShow() {
                    Log.i("onAdShow");
                }

                public void onAdShowError(AdError error) {
                    Log.i("onAdShowError");
                    isLoading = false;
                    showToast("onAdShowError");
                }

                public void onAdDismiss() {

                }

                public void onAdDismiss(SingleFeedAd ad) {
                    Log.i(String.format("onAdDismiss：%s", ad.getPlatform().getId()));
                    showToast(String.format("onAdDismiss：%s", ad.getPlatform().getId()));
                    if (adapter != null) {
                        int removedPosition = adPosMap.get(ad);
                        adapter.removeAD(removedPosition, ad);
                    }
                }

                public void onAdClick() {

                }

                public void onAdClick(SingleFeedAd ad) {
                    if (ad != null) {
                        Log.i(String.format("onAdClick：%s", ad.getPlatform().getId()));
                        showToast(String.format("onAdClick：%s", ad.getPlatform().getId()));
                    }
                }

                public void onDislikeShow() {
                    Log.i("onDislikeShow");
                }

                public void onDislikeSelected(SingleFeedAd ad, String value) {
                    Log.i(String.format("onDislikeSelected：%s：%s", ad.getPlatform().getId(), value));
                    showToast(String.format("onDislikeSelected：%s：%s", ad.getPlatform().getId(), value));
                    if (adapter != null) {
                        int removedPosition = adPosMap.get(ad);
                        adapter.removeAD(removedPosition, ad);
                    }
                }

                public void onDislikeDismiss() {
                    Log.i("onDislikeDismiss");
                }
            });
        }
    }

    private void fillRecyclerViewData() {
        adapter = new FeedAdapter(this, normalDataList, adPosMap);
        recyclerView.setAdapter(adapter);
    }

    private void loadAds(List<SingleFeedAd> adList) {
        int count = adapter.getItemCount();
        int adCount = adDataList.size();
        for (int i = 0; i < ITEMS_COUNT; ++i) {
            normalDataList.add(new NormalItem("No." + (count + i - adCount) + " Normal " + "Data"));
            adapter.notifyItemInserted(count + i);
        }

        for (int i = 0; i < adList.size(); i++) {
            int position = count + FIRST_AD_POSITION + ITEMS_PER_AD * i + i;
            if (position < normalDataList.size()) {
                SingleFeedAd ad = adList.get(i);
                adPosMap.put(ad, position);
                adapter.addAdToPosition(position, adList.get(i));
                adapter.notifyItemInserted(position);
            }
        }
        adDataList.addAll(adList);
    }

    /**
     * 横竖屏切换<br/>
     */
    private void reverseScreenOrientation() {
        boolean isLandscape = getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;

        ViewGroup layout_button = findView(R.id.layout_button);
        layout_button.getLayoutParams().height = isLandscape ? DensityUtils.dp2px(this, 220) : DensityUtils.dp2px(this, 220);

        setRequestedOrientation(isLandscape ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

}